<template>
  <view class="upload-file-wrapper" @click="openPopup">
    <view class="upload-file-content" :class="{ 'file-item': filePDF.url, error: imageError }">
      <block v-if="filePDF.url">
        <text class="file-name">{{ filePDF.fileName }}</text>
        <view class="icon-clear-wrap">
          <ve-icon name="icon-clear" size="32" @click.stop="deleteFile" />
        </view>
      </block>
      <block v-else-if="imageError">
        <!-- 上传失败 -->
        <text class="file-name" @click.stop="retry">上传失败，重试</text>
        <view class="icon-clear-wrap">
          <ve-icon name="icon-clear" size="32" @click.stop="deleteRetry" />
        </view>
      </block>
      <block v-else>
        <!-- 上传中 -->
        <text v-if="progress != 0 && progress != 100" style="margin-right: 4rpx" @click.stop>正在上传 {{ progress }}%</text>
        <text v-else>请选择</text>
      </block>
      <ve-icon name="arrow_right_0" size="32" />
    </view>
  </view>
  <ve-popup :model-value="popupValue" @close="close" mode="bottom" :maskClose="true">
    <view class="add-popup">
      <view class="tlt c1 fs36">请选择上传类型</view>
      <ve-button class="button" size="default" @click="addfile(0)"
        >文件（
        <text v-for="(item, index) in fileTypes" :key="index"> {{ item }} {{ index + 1 != fileTypes.length ? '、' : '' }} </text>
        ）</ve-button
      >
      <ve-button class="button" size="default" @click="addfile(1)">图片</ve-button>
    </view>
  </ve-popup>
</template>

<script setup>
  // #ifdef APP-PLUS
  import permision from '@/utils/permissionCheck/permission.js'
  // #endif
  import { packagedUploadFile } from '@/utils/upload-tool.js'
  import { ref, watch, computed } from 'vue'
  import { getFileSingle } from '@/api/common/index'
  // import { onUnload, onShow } from '@dcloudio/uni-app'

  const popupValue = ref(false)
  const progress = ref(0)
  const imageError = ref(false)
  const fileImage = ref(null) //本地暂存文件（图片）
  const filePDF = ref({
    url: '',
    fileName: '', //本地文件
    fileIdStr: '',
  })
  const props = defineProps({
    fileId: String,
    fileName: String,
    fileIndex: {
      type: [String, Number],
      default: 1,
    },
    fileTypes: {
      type: Array,
      default: () => [],
    },
  })
  const emit = defineEmits(['update:fileId', 'update:fileName', 'change'])
  const openPopup = () => {
    popupValue.value = true
  }
  const close = () => {
    popupValue.value = false
  }

  watch(
    () => props.fileId,
    (newValue, oldValue) => {
      console.log('watch 已触发', newValue)
      if (newValue) {
        getPicture()
      } else {
        filePDF.value = {}
      }
    },
    { deep: true },
  )

  const addfile = (type) => {
    const system = uni.getSystemInfoSync()
    console.log('机型：' + system.osName)
    console.log(type == 0 ? '文件' : '照片')
    // 检测权限
    // 文件
    if (type == 0) {
      if (system.osName == 'android') {
        permision.premissionCheck('READ_EXTERNAL_STORAGE').then((result1) => {
          console.log('result1', result1)
          if (result1 == 1) {
            popupValue.value = false
            uni.navigateTo({
              url: '/pages/utils/uploadFile?fileIndex=' + props.fileIndex + '&fileTypes=' + JSON.stringify(props.fileTypes),
            })
          }
        })
      }
      if (system.osName == 'ios') {
        popupValue.value = false
        uni.navigateTo({ url: '/pages/utils/uploadFile?fileIndex=' + props.fileIndex + '&fileTypes=' + JSON.stringify(props.fileTypes) })
      }
    }
    // 相机和照片
    if (type == 1) {
      if (system.osName == 'android') {
        permision.premissionCheck('CAMERA_EXTERNAL_STORAGE').then((result1) => {
          console.log('result1', result1)
          if (result1 == 1) {
            popupValue.value = false
            photo()
          }
        })
      }
      if (system.osName == 'ios') {
        popupValue.value = false
        photo()
      }
    }
  }
  // 选择照片
  const photo = () => {
    uni.chooseImage({
      count: 1,
      sourceType: ['album', 'camera'],
      sizeType: ['original', 'compressed'],
      success: function (res) {
        console.log(JSON.stringify(res.tempFilePaths))
        fileImage.value = res.tempFilePaths[0]
        if (res.tempFilePaths[0]) {
          uploadImage()
        }
      },
    })
  }
  // 上传照片
  const uploadImage = () => {
    const task = packagedUploadFile({
      filePath: fileImage.value,
      success: (res) => {
        console.log('success-res', res)
        var data = JSON.parse(res.data)
        var result = data.result[0]
        if (data.code == 200) {
          // 上传完成
          progress.value = 100
          emit('update:fileId', result.fileIdStr)
          emit('update:fileName', result.fileName)
          emit('change', result)
          filePDF.value = {
            url: result.openUrl,
            fileName: result.fileName,
            fileIdStr: result.fileIdStr,
          }
        } else {
          uploadError()
        }
      },
      fail: (e) => {
        uploadError()
      },
    })
    task.onProgressUpdate((res) => {
      console.log('progress', res.progress)
      imageError.value = false
      // 由于上传进度只能监听到文件传输过程, progress 为100，不代表上传完成，仅代表传输完成
      let resProgress = res.progress
      if (resProgress == 0) {
        resProgress = 1
      } else if (resProgress >= 99) {
        resProgress = 99
      }
      progress.value = resProgress
    })
  }
  // 照片上传失败
  const uploadError = () => {
    progress.value = 0
    imageError.value = true
  }
  // 重试
  const retry = () => {
    progress.value = 1
    uploadImage()
  }
  // 删除照片
  const deleteFile = () => {
    filePDF.value = {
      url: '',
      fileName: '', //本地文件
      fileIdStr: '',
    }

    emit('update:fileId', '')
    emit('update:fileName', '')
    emit('change', filePDF.value)
  }
  // 删除重试
  const deleteRetry = () => {
    imageError.value = false
  }
  // 获取文件pdf-img
  const getPicture = () => {
    console.log('编辑(详情)时获取文件', props.fileId)
    getFileSingle({ id: props.fileId }).then((res) => {
      if (res.code == 200 && res.result) {
        console.log(res.result.openUrl)
        console.log(res.result.fileIdStr)
        var url = res.result.openUrl
        filePDF.value = {
          url: res.result.openUrl,
          fileName: res.result.originalFileName, //本地文件
          fileIdStr: res.result.fileIdStr,
        }
      }
    })
  }
  uni.$on('getFileObj', (res) => {
    console.log('获取文件obj', res)

    let propFileIndex = props.fileIndex
    let resFileIndex = res.fileIndex
    console.log(propFileIndex, resFileIndex)
    if (propFileIndex == resFileIndex) {
      filePDF.value = {
        url: res.openUrl,
        fileName: res.fileName, //本地文件
        fileIdStr: res.fileIdStr,
      }
      emit('update:fileId', res.fileIdStr)
      emit('update:fileName', res.fileName)
      emit('change', filePDF.value)
    }
  })

  const fileIdPageFlag = computed(() => {
    if (props.fileId) {
      return true
    } else {
      return false
    }
  })

  if (fileIdPageFlag.value) {
    getPicture()
  }
</script>

<style lang="scss" scoped>
  .upload-file-wrapper {
    display: flex;
    align-items: center;
    font-size: 28rpx;
    color: #9ea5bb;
    justify-content: flex-end;
    .upload-file-content {
      display: flex;
      align-items: center;
      justify-content: right;
      .file-name {
        overflow: hidden;
        text-align: right;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
      .icon-clear-wrap {
        padding-left: 10rpx;
        padding-right: 4rpx;
      }
    }
    .file-item {
      color: #191c27;
      width: 390rpx;
    }
    .error {
      color: #9ea5bb;
    }
  }
  .add-popup {
    padding: 0 40rpx 64rpx;
    .tlt {
      margin: 48rpx 0;
      width: 100%;
      text-align: center;
    }
    .button {
      margin-bottom: 32rpx;
    }
  }
</style>
